/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.hauntedhouses.dao;

import cz.muni.fi.pa165.hauntedhouses.entity.Account;
import cz.muni.fi.pa165.hauntedhouses.util.Util;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**This class implements AccountDAO imterface and
 * therefore allows manipulation with accounts.
 *
 * @author Siliarus
 */
@Repository
public class AccountDAOImpl implements AccountDAO{

     @PersistenceContext(type= PersistenceContextType.EXTENDED)
    private EntityManager em;
    
    
    public void setEntityManager(EntityManager em){
        this.em = em;
    }
    
    @Override
    public void create(Account acc) {
        Util.validateAccount(acc);
        if (acc.getId() != null) {
            throw new IllegalArgumentException("ID was already assigned");
        }
        em.persist(acc);
        em.flush();
        em.detach(acc);
    }

    @Override
    public Account get(Long id) {
        if(id == null) {
            throw new IllegalArgumentException("ID is NULL");
        }
        if(id < 0) {
            throw new IllegalArgumentException("ID < 0");
        }
        Account acc = em.find(Account.class, id);
        em.flush();
        em.detach(acc);
        em.flush();
        em.detach(acc);
        em.flush();
        return acc;
    }
    
    @Override
    public Account findByUsername(String username) {
        if(username == null) {
            throw new IllegalArgumentException("Username is NULL");
        }
        Query q = em.createQuery("from Account where username=:username");
        q.setParameter("username", username);
        List<Account> accounts = q.getResultList();
        if (accounts.size() != 1){
            return null;
        } else {
            return accounts.get(0);
        }
        
    }
}
